<template>
  <el-dialog v-model="visible" :title="title" top="5vh" :width="width" destroy-on-close class="word-viewer-dialog">
    <div id="wordContainer" class="word-content-container" />
  </el-dialog>
</template>

<script setup lang="ts">
  import { ref } from 'vue'
  import { renderAsync } from 'docx-preview'
  import { ElMessage } from 'element-plus'

  defineOptions({ name: 'WordViewer' })

  // 响应式数据
  const visible = ref(false)
  const title = ref('Word文档预览')
  const width = ref('80%')

  const docxOptions = {
    className: 'WordViewer-content', // 自定义类名
    inWrapper: false,
    ignoreWidth: true,
    ignoreHeight: false,
    ignoreFonts: true,
    breakPages: false,
    ignoreLastRenderedPageBreak: true,
    experimental: false,
    trimXmlDeclaration: true,
    useBase64URL: false,
    useMathMLPolyfill: false,
    showChanges: false,
    debug: false,
  }

  // 渲染Word文档
  const renderWord = async (url: string) => {
    try {
      const response = await fetch(url)
      if (!response.ok) {
        ElMessage.error('Word文档加载失败！')
        throw new Error('Failed to fetch file')
      }

      const data = await response.blob()
      const container = document.getElementById('wordContainer')

      if (container) {
        // 清空容器
        container.innerHTML = ''

        await renderAsync(data, container, null, docxOptions)

        // 设置样式
        const el = document.querySelector('.WordViewer-content')
        if (el) {
          ;(el as HTMLElement).style.padding = '30px'
        }
      }
    } catch (error) {
      console.error('Word文档渲染失败:', error)
      ElMessage.error('Word文档加载失败')
    }
  }

  // 打开弹框的方法
  const openDialog = async (url: string, dialogTitle?: string, dialogWidth?: string) => {
    if (dialogTitle) title.value = dialogTitle
    if (dialogWidth) width.value = dialogWidth

    visible.value = true

    // 等待DOM更新后再渲染
    await new Promise((resolve) => setTimeout(resolve, 100))
    await renderWord(url)
  }

  // 暴露方法给父组件
  defineExpose({
    openDialog,
  })
</script>

<style scoped>
  /* 对话框样式 */
  .word-viewer-dialog :deep(.el-dialog__body) {
    padding: 0;
    height: 80vh;
    overflow: hidden;
  }

  /* 文档容器样式 */
  .word-content-container {
    height: 80vh;
    overflow-y: auto;
    padding: 20px;
    background: #f5f5f5;
  }

  /* Word文档内容样式 */
  :deep(.WordViewer-content) {
    background: #fff;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    margin: 0 auto;
    max-width: 800px;
  }

  :deep(.WordViewer-content[style]) {
    padding: 30px !important;
  }

  /* 自定义滚动条 */
  .word-content-container::-webkit-scrollbar {
    width: 8px;
  }

  .word-content-container::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 4px;
  }

  .word-content-container::-webkit-scrollbar-thumb {
    background: #c1c1c1;
    border-radius: 4px;
  }

  .word-content-container::-webkit-scrollbar-thumb:hover {
    background: #a8a8a8;
  }
</style>
